package com.example.appmanager.user;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.example.appmanager.Appconfig.Appconfig;
import com.example.appmanager.Appconfig.ToastShow;
import com.example.appmanager.MainActivity;
import com.example.appmanager.R;
import com.example.appmanager.adapter.AppAdapter;
import com.example.appmanager.adapter.CommentsAdapter;
import com.example.appmanager.entity.AppCustomer;
import com.example.appmanager.entity.AppEntity;
import com.example.appmanager.entity.DetailsEntity;
import com.example.appmanager.entity.ReviewTableEntity;
import com.example.appmanager.entity.UserReview;
import com.example.appmanager.services.AllresposeService;
import com.example.appmanager.ui.home.HomeFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.LongDef;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.yanzhenjie.nohttp.NoHttp.getContext;
/*查看APP的详细 信息  对应one_app_info.xml*/
public class OneAppInfo extends AppCompatActivity {
    private String appId;
    private List<DetailsEntity.RowsBean> rowsBeans = new ArrayList<>();
    private AppCustomer appCustomer =  new AppCustomer();
    private DetailsEntity.RowsBean bean = new DetailsEntity.RowsBean();
    private RecyclerView recyclerView;//这个十评论的RecycleView
    private CommentsAdapter adapter;
    private List<UserReview.RowsBean> userReviewRows = new ArrayList<>();
    private TextView textAppName;//APP名字
    private TextView textAppType;//APP类型
    private TextView textAppUpTime;//APP更新时间
    private TextView textAppSize;//APP大小
    private TextView textAppUpInfo;//APP更新内容
    private TextView textCustomerName;//Customer 开发商名字
    private TextView textCustomerAccount;//Customer 开发商账号
    private TextView textCustomerTel;//Customer 开发商电话
    private TextView textCustomerSite;//Customer 网站
    private ImageView imageViewCustomer;//公司logo
    private ImageView imageViewApp;//APp图片  one_app_image
    private ImageView imageViewShare;//点击的分享图片
    private ImageView imageViewComments;//点击的评论图片
    private EditText editTextReview;//这个是评论的框
    private Button button;//install
    private boolean[] bug={false};
    private Map<String,Object> map;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one_app_info);
        initUi();
        //getData(appId);//请求数据
        ifExits(appId);
        ifExitsReview();
        getClickListener();//监听事件
    }
    //这表是查询评论是否存在  如果存在就加入  否则显示暂时没有评论
    private void ifExitsReview() {
    }
    private void getClickListener() {
        /*用户评论按钮*/
        //要得到 用户的账号  评论内容  APP 的ID
        imageViewComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //网络请求插入评论
                Retrofit retrofit = new Retrofit.Builder().baseUrl(Appconfig.BASE_URL)
                        .client(Appconfig.CLIENT) //这是设置请求的时间等信息 连接时间  上传等时间
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                AllresposeService request = retrofit.create(AllresposeService.class);
                //showNormalDialog();
            }
        });
        /*用户的分享图片*/
        imageViewShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast toast = new ToastShow().getToast(getApplicationContext(), "努力与服务商洽谈中！", 1000);
                toast.show();
            }
        });
        /*用户安装的按钮*/
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("appId", String.valueOf(appCustomer.getId()));
                JSON app = (JSON) JSONObject.toJSON(appCustomer);
                Log.d("OneAppinfo", app.toJSONString());
                bundle.putString("AppAdapter", String.valueOf(app));
                bundle.putString("userLoginInfo", String.valueOf(100));//从用户主页跳转到我的下载里面
                Intent intent = new Intent(getApplicationContext(), HomeFragment.class);//这里跳转到下载页面
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();

    }
    //这里是设置界面上的数据！！
    private void setScreen(AppCustomer appCustomer1) {
        //String app = String.valueOf(getIntent().getExtras().get("AppAdapter"));// bundle.putString("appId",String.valueOf(appEntity.getId()));

        JSON json = (JSON) JSONObject.toJSON(appCustomer1);
        Log.d("0002",json.toJSONString());
        if (!appCustomer1.equals(null)) {
            //
            //bean = rowsBeans.get(0);
            textAppName.setText(appCustomer1.getAppname().trim());//APP名字
            textAppType.setText(appCustomer1.getType());//APP类型
            textAppUpTime.setText(appCustomer1.getCtime());//APP更新时间
            textAppSize.setText(appCustomer1.getCsize());//APP大小
            textAppUpInfo.setText(appCustomer1.getUpinfo());//APP更新内容
            textCustomerName.setText(appCustomer1.getCname());//Customer 开发商名字
            textCustomerAccount.setText(appCustomer1.getAccountc());//Customer 开发商账号
            textCustomerTel.setText(appCustomer1.getTelnum());//Customer 开发商电话
            textCustomerSite.setText(appCustomer1.getCsite());//Customer 网站
            if (appCustomer1.getCpicture().equals(null) || appCustomer1.getCpicture().equals("") || appCustomer1.getCpicture().equals(" ")) {
                Glide.with(getApplicationContext()).load(Appconfig.BASE_IMAG + appCustomer1.getCpicture()).into(imageViewCustomer);//公司logo

            } else {
                Glide.with(getApplicationContext()).load(Appconfig.BASE_IMAG + "APP.png").into(imageViewCustomer);//公司logo
            }

            Glide.with(getApplicationContext()).load(Appconfig.BASE_IMAG + appCustomer.getApicture()).into(imageViewApp);//APp图片  one_app_image


        }
    }
    private void initUi() {
        //bundle.putString("appId",String.valueOf(appEntity.getId()));
        // bundle.putString("uName",uName);
        appId = (String) getIntent().getExtras().get("appId");
        String uname = (String) getIntent().getExtras().get("uName");
        Log.d("OneAppInfo的信息：+", appId+"-->账号"+uname);
        adapter = new CommentsAdapter(getApplicationContext(), null);
        recyclerView = findViewById(R.id.comments);
        textAppName = findViewById(R.id.app_name);//APP名字
        textAppType = findViewById(R.id.app_type);//APP类型
        textAppUpTime = findViewById(R.id.app_time);//APP更新时间
        textAppSize = findViewById(R.id.app_size);//APP大小
        textAppUpInfo = findViewById(R.id.app_use_upInfo);//APP更新内容
        textCustomerName = findViewById(R.id.customerName);//Customer 开发商名字
        textCustomerAccount = findViewById(R.id.customerAccount);//Customer 开发商账号
        textCustomerTel = findViewById(R.id.customerTel);//Customer 开发商电话
        textCustomerSite = findViewById(R.id.customerSite);//Customer 网站
        imageViewApp = findViewById(R.id.one_app_image);//APP 的 图片
        imageViewCustomer = findViewById(R.id.customer_image);//APP信息的主图
        imageViewShare = findViewById(R.id.share);//分享的图片
        imageViewComments = findViewById(R.id.user_comments);//评论
        editTextReview = findViewById(R.id.one_app_texReview);
        button = findViewById(R.id.one_app_install);//安装按钮

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
   /* private void getData(String aid) {
        //第一步先判断这个aid是否亦评论？？
        //如果有就查询所有在信息  开发商  APP 用户  评论表
        //如果没有就查询 开发商  APP 两个表胡信息
        adapter.setData(getApplicationContext(), userReviewRows);
        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Appconfig.BASE_URL)
                .client(Appconfig.CLIENT) //这是设置请求的时间等信息 连接时间  上传等时间
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AllresposeService request = retrofit.create(AllresposeService.class);
        Call<ReviewTableEntity> appCall = request.getApp(aid);
        appCall.enqueue(new Callback<ReviewTableEntity>() {
            @Override
            public void onResponse(Call<ReviewTableEntity> call, Response<ReviewTableEntity> response) {
                //assert response.body() != null;
                int size = response.body().getRows().size();
                Log.d("AppTypeShow", "请求chenggong!!!!长度是："+size);
                if (size>0){
                    bug[0] = true;
                    Retrofit retrofit = new Retrofit.Builder().baseUrl(Appconfig.BASE_URL)
                            .client(Appconfig.CLIENT) //这是设置请求的时间等信息 连接时间  上传等时间
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    AllresposeService request = retrofit.create(AllresposeService.class);
                    Call<DetailsEntity> appCall = request.getAllInfo(aid);
                    appCall.enqueue(new Callback<DetailsEntity>() {
                        @Override
                        public void onResponse(Call<DetailsEntity> call, Response<DetailsEntity> response) {
                            assert response.body() != null;
                            rowsBeans = response.body().getRows();
                            Log.d("OneAppInfo111", (JSONArray.toJSON(rowsBeans).toString()));

                            //设置界面上的数据
                            setScreen(appCustomer);
                            adapter.setData(getApplicationContext(), rowsBeans);
                            adapter.notifyDataSetChanged();
                            recyclerView.setAdapter(adapter);
                            if (rowsBeans.isEmpty()) {
                            }
                        }
                        @Override
                        public void onFailure(Call<DetailsEntity> call, Throwable t) {
                            // recyclerView.setAdapter(adapter);
                            Log.d("AppTypeShow", "请求错误" + t.getMessage());
                        }
                    });
                }else {
                    bug[0] =false;
                    //Toast.makeText(getContext(),"还没有评论哦！",Toast.LENGTH_LONG).show();
                    Retrofit retrofit = new Retrofit.Builder().baseUrl(Appconfig.BASE_URL)
                            .client(Appconfig.CLIENT) //这是设置请求的时间等信息 连接时间  上传等时间
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    AllresposeService request = retrofit.create(AllresposeService.class);
                    Call<AppCustomer> appCall= request.getAppCustomer(aid);
                    appCall.enqueue(new Callback<AppCustomer>() {
                        @Override
                        public void onResponse(Call<AppCustomer> call, Response<AppCustomer> response) {
                            assert response.body() != null;
                            //设置界面上的数据
                            appCustomer = response.body();
                            setScreen(appCustomer);

                        }
                        @Override
                        public void onFailure(Call<AppCustomer> call, Throwable t) {
                            // recyclerView.setAdapter(adapter);
                            Log.d("AppTypeShow", "请求错误" + t.getMessage());
                        }
                    });
                }


            }
            @Override
            public void onFailure(Call<ReviewTableEntity> call, Throwable t) {
                // recyclerView.setAdapter(adapter)
                bug[0] =false;
                Log.d("AppTypeShow", "请求错误112" + t.getMessage());
            }
        });
        *//*if (ifExits(appId)) { //如果有就查询所有在信息  开发商  APP 用户  评论表

        }else {// //如果没有就查询 开发商  APP 两个表的信息
            Log.d("OneAppInfo","该appid在评论表中已经存在可以直接查询了，，，");
        }*//*
    }*/
    // 判断APP的ID是不是在评论表中？
    private void  ifExits(String aid) {
        //第一步先判断这个aid是否亦评论？？
        //如果有就查询所有在信息  开发商  APP 用户  评论表
        //如果没有就查询 开发商  APP 两个表胡信息
        adapter.setData(getApplicationContext(), userReviewRows);
        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
        //===========================================
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Appconfig.BASE_URL)
                .client(Appconfig.CLIENT) //这是设置请求的时间等信息 连接时间  上传等时间
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AllresposeService request = retrofit.create(AllresposeService.class);
        Call<AppCustomer> appCall= request.getAppCustomer(aid);
        appCall.enqueue(new Callback<AppCustomer>() {
            @Override
            public void onResponse(Call<AppCustomer> call, Response<AppCustomer> response) {
                assert response.body() != null;
                //设置界面上的数据
                appCustomer = response.body();
                Log.d("0002",appCustomer.getCname());
                Log.d("0002",appCustomer.getAppname());
                Log.d("0002",appCustomer.getCtime());
                setScreen(appCustomer);
                Call<UserReview> appReview = request.getUserReview(String.valueOf(aid));//查询评论的用户和 评论内容
                appReview.enqueue(new Callback<UserReview>() {
                    @Override
                    public void onResponse(Call<UserReview> call, Response<UserReview> response) {
                        userReviewRows = response.body().getRows();
                        adapter.setData(getApplicationContext(), userReviewRows);
                        adapter.notifyDataSetChanged();
                        recyclerView.setAdapter(adapter);
                        if (rowsBeans.isEmpty()) {
                        }
                    }

                    @Override
                    public void onFailure(Call<UserReview> call, Throwable t) {

                    }
                });
            }
            @Override
            public void onFailure(Call<AppCustomer> call, Throwable t) {
                // recyclerView.setAdapter(adapter);
                Log.d("AppTypeShow", "请求错误" + t.getMessage());
            }
        });
        //===========================================
    }

    private void showNormalDialog() {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setIcon(R.drawable.dialog);
        normalDialog.setPositiveButton("返回",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.cancel();
                    }
                });
        normalDialog.setNegativeButton("发布",
                (dialog, which) -> {
                    //...To-do
                    Intent intent = new Intent(this, Login.class);
                    startActivity(intent);//返回登录！！！
                });
        // 显示
        normalDialog.show();
    }

}
